//
//  DeviceFinder.m
//  PacketSniffer
//
//  Created by nark on 15/04/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "PSDeviceFinder.h"


@implementation PSDeviceFinder


- (PSDevice *)lookupForDefaultDevice {
	char *dev;
	
	dev = pcap_lookupdev(errbuf);
	if (dev == NULL) {
		NSString *message = [NSString stringWithFormat:@"Couldn't find default device: %s", errbuf];
		PSError *error = [[PSError alloc] initWithType:PSErrorTypeCritical
											   message:message 
												 infos:nil];
		[PSError notifyError:error];
		return nil;
		
	} else {
		PSDevice *device = [[PSDevice alloc] initWithName:[NSString stringWithUTF8String:dev]];
		device = [self getDeviceProperties:device];
		return device;
		
	}
	return nil;
}


- (NSMutableArray *)lookupForAllDevices {
	NSMutableArray *devices = [[NSMutableArray alloc] init];
	pcap_if_t *alldevs; /* device list */
	pcap_if_t *d;		/* temp device */
	
	/* Find all allowed devices */
	if (pcap_findalldevs(&alldevs, errbuf) == -1) {
		NSString *message = [NSString stringWithFormat:@"Error in pcap_findalldevs: %s", errbuf];
		PSError *error = [[PSError alloc] initWithType:PSErrorTypeCritical
											   message:message 
												 infos:nil];
		[PSError notifyError:error];
		return nil;
	}
	
	/* Convert devices to Device objects */
	for(d = alldevs; d; d = d->next)
	{
		PSDevice *device = [[PSDevice alloc] initWithName:[NSString stringWithUTF8String:d->name]];
		
		if(d->description != NULL) {
			[device setValue:[NSString stringWithUTF8String:d->description] forKey:@"description"];
		}
		
		device = [self getDeviceProperties:device];
		[devices addObject:device];
	}
	return devices;
}


- (PSDevice *)getDeviceProperties:(PSDevice *)_device {
	bpf_u_int32 mask;				/* Our netmask */
    bpf_u_int32 net;				/* Our IP */
	const char *dev = [[_device name] UTF8String];
	
	/* Find the properties for the device */
    if (pcap_lookupnet(dev, &net, &mask, errbuf) == -1) {
        fprintf(stderr, "Couldn't get netmask for device %s: %s\n", dev, errbuf);
		NSString *message = [NSString stringWithFormat:@"Couldn't get netmask for device %s: %s", dev, errbuf];
		PSError *error = [[PSError alloc] initWithType:PSErrorTypeCritical
											   message:message 
												 infos:nil];
		[PSError notifyError:error];
        net = 0;
        mask = 0;
    }
	
	[_device setNet:net];
	[_device setMask:mask];
	
	return _device;
}


@end
